package com.hdhere.application.service;

import com.hdhere.application.Repository.media.VideoPostRepository;
import com.hdhere.application.Repository.media.VideoRepository;
import com.hdhere.domain.common.Pagination;
import com.hdhere.domain.common.enums.RowState;
import com.hdhere.domain.media.QVideoPost;
import com.hdhere.domain.media.VideoPost;
import com.hdhere.domain.media.page.VideoPostPagination;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.Expressions;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class VideoPostService {

    @Value("${server.upload-path}")
    private String uploadPath;

    @Autowired
    private VideoPostRepository videoPostRepository;

    @Autowired
    private VideoRepository videoRepository;

    public VideoPost getOne(Long id){
        return videoPostRepository.getOne(id);
    }

    /**
     * @Description: 添加默认设为已发布（以后改为发布单独操作，和修改分开）
     * @param:  * @param null
     * @Author: dustin
     * @Date: 2019-03-09 10:02
     */
    @Transactional
    public void save(VideoPost videoPost){
        //第一次发布，改视频发布状态
        if(videoPost.getId() == null){
            videoRepository.updatePostState(videoPost.getVideoId(), RowState.Effective.getId());
        }
        videoPost.resetData();
        videoPostRepository.save(videoPost);
    }

    public Pagination getPage(VideoPostPagination page){
        var q = QVideoPost.videoPost;
        Predicate pre = Expressions.asBoolean(true).isTrue();

        if(page.getCatePath() != null)
            pre = ExpressionUtils.and(pre, q.catePath.contains(page.getCatePath()));
        if(StringUtils.isNotBlank(page.getTitle()))
            pre = ExpressionUtils.and(pre, q.title.like("%"+page.getTitle()+"%"));


        Page<VideoPost> date = videoPostRepository.findAll(pre, page);
        page.setPage(date);
        return page;
    }

    @Transactional
    public void delete(Long id){
        var post = getOne(id);
        //更改视频发布状态
        videoRepository.updatePostState(post.getVideoId(), RowState.Draft.getId());
        //删除发布
        String[] thumbnails;
        if(StringUtils.isNotBlank(post.getThumbnail()) && (thumbnails = post.getThumbnail().split(",")).length > 0){
            for(String img:thumbnails){
                var file = new File(uploadPath + img);
                if(file.exists())
                    file.delete();
            }
        }
        videoPostRepository.delete(post);
    }

    /**
     * @Description: 删除一张缩略图
     * @param:  * @id 主键
     * @param:  * @fileName 略图图文件名
     * @Author: dustin
     * @Date: 2019-03-31 12:46
     */
    //@Transactional
    public boolean deleteThumbnail(Long id, String fileName){
        var post = getOne(id);
        String thumbnail;
        List<String> thumbnails;
        if(post == null || StringUtils.isBlank(thumbnail=post.getThumbnail())
                || (thumbnails = new ArrayList<>(Arrays.asList(thumbnail.split(",")))).size() == 0)
            return false;

        thumbnails.removeIf(x->fileName.equals(x));
        post.setThumbnail(String.join(",", thumbnails));

        videoPostRepository.save(post);

        File serverFile = new File(uploadPath + fileName);
        serverFile.delete();

        return true;
    }

}
